package com.meelive.ingkee.iknetwork.diagnose

import android.content.res.ColorStateList
import android.graphics.drawable.*
import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.fragment.app.Fragment
import com.meelive.ingkee.base.utils.text.StringUtils
import com.meelive.ingkee.iknetwork.diagnose.api.IKNetworkDiagnoseContract
import com.meelive.ingkee.iknetwork.diagnose.model.CopyViewConfig
import com.meelive.ingkee.iknetwork.diagnose.model.TitleViewConfig
import com.meelive.ingkee.iknetwork.diagnose.util.DiagnosePares
import com.meelive.ingkee.iknetwork.diagnose.util.InKeNetworkDiagnoseUtil

class DefaultCheckNetworkFragment : Fragment(), IKNetworkDiagnoseContract {

    private var isFinishFlag: Boolean = false

    private var checkResultTextView: TextView? = null
    private var copyCheckInfoBtn: Button? = null
    private var backContainerView: FrameLayout? = null
    private var backImageView: ImageView? = null
    private var titleTextView: TextView? = null
    private var checkNetworkScrollView: ScrollView? = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_default_check_network, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        isFinishFlag = false

        checkResultTextView = view.findViewById(R.id.check_result)
        copyCheckInfoBtn = view.findViewById(R.id.copy_check_info)
        backContainerView = view.findViewById(R.id.back_container)
        backImageView = view.findViewById(R.id.back)
        titleTextView = view.findViewById(R.id.title)
        checkNetworkScrollView = view.findViewById(R.id.check_network_scroll)

        checkResultTextView?.also {
            it.movementMethod = ScrollingMovementMethod()
        }

        copyCheckInfoBtn?.also {
            it.setOnClickListener {
                if (isFinishFlag) {
                    checkResultTextView?.also {
                        showToast("已将诊断信息拷贝到粘贴板")
                        val networkDiagnoseLog = it.text.toString()
                        InKeNetworkDiagnoseUtil.addToClipboardWithoutToast(networkDiagnoseLog)
                    }
                }
            }
            it.isEnabled = false
        }

        backContainerView?.setOnClickListener {
            activity?.finish()
        }

        arguments?.apply {
            if (this.containsKey(CheckNetworkActivity.COPY_VIEW_CONFIG)) {
                val viewConfigStr = getString(CheckNetworkActivity.COPY_VIEW_CONFIG)

                viewConfigStr.takeUnless { StringUtils.isEmpty(it) }?.also {
                    val viewConfig = DiagnosePares.parseJson(it, CopyViewConfig::class.java)
                    if (viewConfig != null) {
                        handleViewConfig(viewConfig)
                    }
                }
            }

            if (this.containsKey(CheckNetworkActivity.TITLE_VIEW_CONFIG)) {
                val viewConfigStr = getString(CheckNetworkActivity.TITLE_VIEW_CONFIG)

                viewConfigStr.takeUnless { StringUtils.isEmpty(it) }?.also {
                    val viewConfig = DiagnosePares.parseJson(it, TitleViewConfig::class.java)
                    if (viewConfig != null) {
                        backImageView?.setColorFilter(viewConfig.backViewColor)
                        titleTextView?.setTextColor(viewConfig.titleColor)
                    }
                }
            }
        }
    }

    private fun showToast(content: String) {
        Toast.makeText(context, content, Toast.LENGTH_LONG).show()
    }

    private fun handleViewConfig(viewConfig: CopyViewConfig) {
        (findStateListChildDrawable(0) as? GradientDrawable)?.apply {
            viewConfig.pressBg?.also {
                setColor(it.color)
                cornerRadius = it.radius
            }
        }

        (findStateListChildDrawable(1) as? ColorDrawable)?.apply {
            viewConfig.unPressBg?.also {
                color = it.color
            }
        }

        (findStateListChildDrawable(2) as? GradientDrawable)?.apply {
            if (viewConfig.unPressBg != null) {
                setColor(viewConfig.unPressBg.color)
            }
            if (viewConfig.pressBg != null) {
                cornerRadius = viewConfig.pressBg.radius
            }
            setStroke(viewConfig.strokeWidth, viewConfig.strokeColor)
        }

        copyCheckInfoBtn?.also {
            it.setTextSize(viewConfig.textSize.first, viewConfig.textSize.second)

            it.setTextColor(
                    ColorStateList(arrayOf(intArrayOf(android.R.attr.state_pressed), intArrayOf(-android.R.attr.state_pressed)),
                            intArrayOf(viewConfig.textColor.first, viewConfig.textColor.second))
            )
        }
    }

    private fun findStateListChildDrawable(index: Int): Drawable? {
        return (copyCheckInfoBtn?.background as? StateListDrawable)?.let {
            (it.constantState as? DrawableContainer.DrawableContainerState)?.getChild(index)
        }
    }

    override fun showMessage(message: String?) {
        if (!StringUtils.isEmpty(message)) {
            checkResultTextView?.text = message
            checkNetworkScrollView?.fullScroll(ScrollView.FOCUS_DOWN)
        }
    }

    override fun messageShowComplete(result: String?) {
        showToast("诊断完成")
        changeUIState()
    }

    override fun messageShowError(result: String?) {
        showToast("诊断过程出现了一点小问题")
        changeUIState()
    }

    private fun changeUIState() {
        isFinishFlag = true
        copyCheckInfoBtn?.also {
            it.isEnabled = true
            it.text = "复制诊断报告"
        }
    }
}